//index.js
//获取应用实例
/*
* 输入的坐标是百度坐标
* 定位到的是火星坐标
*
* */
const app = getApp()
var coordtransform = require('../../utils/coordtransform/index.js');//

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    stores:[
      {
        id:1,
        address:"福州市鳌峰广场601",
        distance:0,
        lat:'26.062336',
        lng:'119.344077',
        storename:'福州鳌峰广场店',
      },
      {
        id:2,
        address:"上海市静安区运城路623号",
        distance:0,
        lat:"31.281734",
        lng:'121.440057',
        storename:"上海大宁公园店",
      },
      {
        id:3,
        address:"广东省广州市越秀区中山二路74",
        distance:0,
        lat:"23.132013",
        lng:"113.295243",
        storename:"广东中山医院店",
      },
      {
        id:4,
        address:"北京市东城区王府井大街16-2号",
        distance:0,
        lat:"39.928789",
        lng:"116.417649",
        storename:"北京首都剧场店",
      },
    ]
  },
  //事件处理函数
  bindViewTap: function() {

  },
  onLoad: function () {

  },
  getUserInfo: function(e) {
    var that = this;
    calcdistance(that,that.data.stores);
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }
})


function calcdistance(that,stores){
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy
        that.setData({
          latitude: latitude,
          longitude: longitude,
        })
        for (var i = 0; i < stores.length; i++) {
          var distance = getDistance(that.data.longitude, that.data.latitude, stores[i].lng, stores[i].lat);
          stores[i].distance = distance;

        }
        for(var storeid = stores.length-1;storeid>0;storeid--){
          for(var j=0;j<storeid;j++){
            if(parseFloat(stores[j].distance)>parseFloat(stores[j+1].distance)){
              var temp = stores[j];
              stores.splice(j,1,stores[j+1]);
              stores.splice(j+1,1,temp);
            }
          }
        }
        that.setData({
          stores:stores
        });
      }
    })
}

function getDistance(lat1, lng1, lat2, lng2) {
  //后面两个参数传入的是百度坐标

  lat1 = lat1 || 0;
  lng1 = lng1 || 0;
  lat2 = lat2 || 0;
  lng2 = lng2 || 0;

  var coorfinatearr = coordtransform.bd09togcj02(lng2,lat2);//百度坐标转火星坐标(国测局坐标)
  lng2 = coorfinatearr[0];
  lat2 = coorfinatearr[1];
  var rad1 = lat1 * Math.PI / 180.0;
  var rad2 = lat2 * Math.PI / 180.0;
  var a = rad1 - rad2;
  var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;

  var r = 6378137;
  return ((r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)))) / 1000).toFixed(2)
}
